﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

/**
 * 血条
 */
public class ItemEntityHP : MonoBehaviour{
    public Image imgHpGary;
    public Image imgHpRed;
    public Animation criticalAni;
    public Text txtCritical;
    public Animation dodgeAni;
    public Text txtDodge;
    public Animation hpAni;
    public Text txtHp;

    private int hpVal = 0;
    private RectTransform rect;
    private Transform rootTrans;
    private float scaleRate = 1.0f * Constants.ScreenStandardHeight / Screen.height;
    
    public void SetCritical(int critical){
        criticalAni.Stop();
        txtCritical.text = "暴击 " + critical;
        criticalAni.Play();
    }
    
    public void SetDodge(){
        dodgeAni.Stop();
        dodgeAni.Play();
    }

    public void SetHurt(int hurt){
        hpAni.Stop();
        txtHp.text = "-" + hurt;
        hpAni.Play();
    }

    private float currentPrg;
    private float targetPrg;
    public void SetHpVal(int oldVal, int newVal){
        currentPrg = oldVal * 1.0f / hpVal;
        targetPrg = newVal * 1.0f / hpVal;
        imgHpRed.fillAmount = targetPrg;
    }

    public void InitItemInfo(Transform trans, int hp){
        rect = transform.GetComponent<RectTransform>();
        rootTrans = trans;
        hpVal = hp;
        imgHpGary.fillAmount = 1;
        imgHpRed.fillAmount = 1;
    }

    private void Update(){
        // if (Input.GetKeyDown(KeyCode.Space)){
        //     SetCritical(999);
        //     SetHurt(996);
        // }
        //
        // if (Input.GetKeyDown(KeyCode.A)){
        //     SetDodge();
        // }

        Vector3 screenPos = Camera.main.WorldToScreenPoint(rootTrans.position);
        rect.anchoredPosition = screenPos * scaleRate;

        UpdateMixBlend();
        imgHpGary.fillAmount = currentPrg;
    }

    private void UpdateMixBlend(){
        if (Mathf.Abs(currentPrg - targetPrg) < Constants.AccelerHpSpeed * Time.deltaTime){
            currentPrg = targetPrg;
        }
        else if(currentPrg > targetPrg){
            currentPrg -= Constants.AccelerHpSpeed * Time.deltaTime;
        }
        else{
            currentPrg += Constants.AccelerHpSpeed * Time.deltaTime;
        }
    }
}